package org.smile.bootstrap;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

public class Bootstrap {
    //空目录
    static  String EMPTY="";
    /**程序主方法*/
    public final static void main(String[] args) throws Exception {
        ClassLoader parentClassLoader = Bootstrap.class.getClassLoader();
        //看当前目录是否存在lib目录
        String userDir = System.getProperty("user.dir");
        File file = new File(userDir+"/lib");
        BootstrapClassLoader classLoader = null;
        if(file.exists()&&file.isDirectory()){//是目录的情况下
            classLoader = new BootstrapClassLoader(file,parentClassLoader);
        }else{
            classLoader=new BootstrapClassLoader(parentClassLoader);
        }
        String appRoot =EMPTY ;
        if(args.length>0){
            appRoot=args[0];
        }else{
            File argsFile=new File(userDir+"/bootstrap.ini");
            if(argsFile.exists()){
                InputStream is =new FileInputStream(argsFile);
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    List<String> strs = new LinkedList<>();
                    String line = null;
                    int index = 0;
                    while (true) {
                        line = reader.readLine();
                        if (line == null || "".equals(line.trim())) {
                            break;
                        }
                        if (index == 0) {
                            appRoot = line;
                        }
                        strs.add(line);
                    }
                    args = strs.toArray(new String[strs.size()]);
                }finally {
                    try {
                        is.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }
        String[] params =new String[0];
        if(args.length>1){
            params=new String[args.length-1];
            System.arraycopy(args,1,params,0,params.length);
        }
        try {
            Class scannerClass = classLoader.loadClass(BootstrapStartScanner.class.getName());
            BootstrapStartScanner scanner= (BootstrapStartScanner) scannerClass.getConstructor(ClassLoader.class,String.class).newInstance(classLoader,appRoot);
            scanner.start(params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
